﻿using DDD.Application.Commands.UserCommand.CreateUser;
using DDD.Application.Commands.UserCommand.DeleteUserById;
using DDD.Application.Commands.UserCommand.UpdateUserById;
using DDD.Application.Queries.UserQuery.GetUserById;
using DDD.Application.Queries.UserQuery.GetUserPage;
using DDD.Common.Const;
using DDD.Core.Result;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using DDD.Application.Queries.UserQuery.ExportUser;

namespace DDD.Api.Controllers
{
    [ApiExplorerSettings(GroupName = SwaggerConst.Group.BASIC, IgnoreApi = false)]
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IMediator _mediator;

        public UserController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 根据id获取用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id:required}")]
        public async Task<ApiResult<GetUserByIdVO>> GetUserByIdQuery(Guid id)
        {
            return await _mediator.Send(new GetUserByIdQuery()
            {
                Id = id
            });
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<Guid>> CreateUser(CreateUserCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 根据用户id修改用户信息
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult<bool>> UpdateUserById(UpdateUserByIdCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 根据用户Id删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id:guid}")]
        public async Task<ApiResult<bool>> DeleteUserById(Guid id)
        {
            return await _mediator.Send(new DeleteUserByIdCommand()
            {
                Id = id
            });
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        [HttpPost("page")]
        public async Task<ApiResult<GetUserPageVO>> GetUserPage(GetUserPageQuery query)
        {
            return await _mediator.Send(query);
        }

        /// <summary>
        /// 导出用户为excel
        /// </summary>
        /// <returns></returns>
        [HttpPost("export")]
        public async Task<FileResult> Export()
        {
            var result = await _mediator.Send(new ExportUserQuery());
            return File(result.Data, "application/octet-stream", $"用户信息-{DateTime.Now.Date.ToString("yyyy-MM-dd")}.xlsx");
        }
    }
}
